<template>
  <div>
    <h2>编辑商品</h2>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/AdminMain/AdminHome">主页</el-breadcrumb-item>
      <el-breadcrumb-item to="/AdminMain/GoodsManager">商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 20px;">
      <el-form :model="form" label-width="100px">
        <el-form-item label="商品ID">
          <el-input v-model="form.gid" readonly />
        </el-form-item>

        <el-form-item label="商品名称">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品价格">
          <el-input v-model.number="form.goodsPrice" type="number" placeholder="请输入价格" />
        </el-form-item>

        <el-form-item label="商品类型">
          <el-input v-model="form.goodsType" placeholder="请输入类型" />
        </el-form-item>

        <el-form-item label="商品图片">
          <el-upload
              class="upload-demo"
              :action="'/server/file/uploadImage'"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="beforeUpload"
          >
          <el-button type="primary">点击上传</el-button>
          </el-upload>
          <div v-if="form.goodsImage" style="margin-top: 10px;">
            <img :src="form.goodsImage" alt="商品图片" style="width: 120px; border: 1px solid #ccc;" />
          </div>
        </el-form-item>

        <el-form-item label="商品库存">
          <el-input v-model.number="form.goodsStock" type="number" placeholder="请输入库存数量" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认修改</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const gid = route.query.gid

const form = ref({
  gid: '',
  goodsName: '',
  goodsPrice: '',
  goodsType: '',
  goodsImage: '',
  goodsStock: ''
})

// 加载商品详情
onMounted(() => {
  if (!gid) {
    ElMessage.error('缺少商品ID')
    return
  }

  axios.get('/server/goods/findById', { params: { gid } })
      .then(response => {
        if (response.data.code === 200) {
          const data = response.data.data
          form.value = {
            gid: data.gid,
            goodsName: data.goodsName,
            goodsPrice: Number(data.goodsPrice),
            goodsType: data.goodsType,
            goodsImage: data.goodsImages,
            goodsStock: Number(data.goodsInventory)
          }
        } else {
          ElMessage.error('获取商品信息失败: ' + (response.data.message || '未知错误'))
        }
      })
      .catch(error => {
        console.error('加载商品信息失败:', error)
        ElMessage.error('请求出错，无法获取商品信息')
      })
})

// 提交修改
const onSubmit = () => {
  axios.put('/server/goods/update', {
    gid: form.value.gid,
    goodsName: form.value.goodsName,
    goodsPrice: form.value.goodsPrice,
    goodsType: form.value.goodsType,
    goodsImages: form.value.goodsImage,
    goodsInventory: form.value.goodsStock
  })
      .then(response => {
        if (response.data.code === 200) {
          ElMessage.success('修改成功')
          router.push('/AdminMain/GoodsManager')
        } else {
          ElMessage.error('修改失败: ' + (response.data.message || '未知错误'))
        }
      })
      .catch(error => {
        console.error('修改失败:', error)
        ElMessage.error('请求失败，修改未完成')
      })
}

// 取消返回
const onCancel = () => {
  router.push('/AdminMain/GoodsManager')
}

// 上传成功回调
const handleUploadSuccess = (response) => {
  if (response.code === 200 && response.data) {
    form.value.goodsImage = response.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImage) ElMessage.error('只能上传图片类型文件')
  if (!isLt2M) ElMessage.error('图片大小不能超过 2MB')
  return isImage && isLt2M
}
</script>

<style scoped>
.upload-demo {
  display: flex;
  flex-direction: column;
}
</style>
